package com.xjz.model.dto.post;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.xjz.model.entity.Post;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * ClassName: PostEsDTO
 * Package: com.xjz.model.dto.post
 * Description:
 *  ES包装类
 * @Author 许小健
 * @Create 2025/8/2 15:29
 * @Version 1.0
 */

//TODO: 取消注释开启ES（须先配置ES）
@Document(indexName = "post")
@Data
public class PostEsDTO implements Serializable {

    private static final long serialVersionUID = -2115210032573425560L;

    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    /**
     * id
     */
    @Id
    private Long id;

    /**
     * 标题
     */
    private String title;

    /**
     * 内容
     */
    private String content;

    /**
     * 标签列表
     */
    private List<String> tags;

    /**
     * 点赞数
     */
    private Integer thumbNum;

    /**
     * 收藏数
     */
    private Integer favourNum;

    /**
     * 创建用户id
     */
    private Long userId;

    /**
     * 创建时间
     */
    @Field(index = false,store = true,type = FieldType.Date,format = {},pattern = DATE_TIME_PATTERN)
    private Date createTime;

    @Field(index = false,store = true,type = FieldType.Date,format = {},pattern = DATE_TIME_PATTERN)
    private Date updateTime;

    /**
     * 是否删除
     */
    private Integer isDelete;

    /**
     * 对象转包装类
     * @param post
     * @return
     */
    public static PostEsDTO objToDto(Post post) {
        if (post == null) {
            return null;
        }

        PostEsDTO postEsDTO = new PostEsDTO();
        BeanUtil.copyProperties(post, postEsDTO);
        String tagsStr = post.getTags();
        if (StringUtils.isNotBlank(tagsStr)) {
            postEsDTO.setTags(JSONUtil.toList(tagsStr, String.class));
        }

        return postEsDTO;
    }

    /**
     * 包装类转对象
     * @param postEsDTO
     * @return
     */
    public static Post dtoToObj(PostEsDTO postEsDTO) {
        if (postEsDTO == null) {
            return null;
        }

        Post post = new Post();
        BeanUtil.copyProperties(postEsDTO, post);
        List<String> tagList = postEsDTO.getTags();
        if (CollectionUtil.isNotEmpty(tagList)) {
            post.setTags(JSONUtil.toJsonStr(tagList));
        }

        return post;
    }
}
